interface Action{
    type:string;
    payload?:any;
}
//T 泛型 为了简便代码创造的类型的定义
interface Reducer<T>{
    (state:T,action:Action):T;
}
//订阅函数的接口
interface ListenerCallBack{
    ():void
}
//取消订阅函数的接口
interface UnsubscribeCallBack{
    ():void
}
class Store <T>{
    private _state:T;
    private _listeners:ListenerCallBack[]=[];
    constructor(
        private reducer:Reducer<T>,
        initialState:T
        ){
            this._state=initialState
        }
    getState():T{
        return this._state
    }
    dispatch(action:Action):void{
        this._state=this.reducer(this._state,action)
        this._listeners.forEach((listener:ListenerCallBack)=>listener())
    }
    subscribe(listener:ListenerCallBack):UnsubscribeCallBack{
        this._listeners.push(listener)
        return ()=>{
            this._listeners=this._listeners.filter(l=>l!=listener)
        }
    }
}
let reducer:Reducer<number>=(state:number,action:Action)=>{
    switch(action.type){
        case 'INCREMENT':
            return state+1;
        case 'DECREMENT':
            return state-1;
        case 'PLUS':
            return state+action.payload
        default : return state
    }
}
let incrementAction:Action= {
    type:'INCREMENT'
}
let decrementAction:Action={
    type:'DECREMENT'
}
let plusAction:Action={
    type:'PLUS',
    payload:9
}

let store=new Store<number>(reducer,0)
console.log(store.getState())
const unsubscribe=store.subscribe(()=>{
    console.log('观察者模式查看状态:' +store.getState())
})
store.dispatch(incrementAction)
console.log(store.getState())


store.dispatch(decrementAction)
console.log(store.getState())

unsubscribe()
store.dispatch(decrementAction)
console.log(store.getState())
store.dispatch(plusAction)
console.log(store.getState())
